package com.example.mobile1931605061xhj0604;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private Button btnMainBind;
    private Button btnMainStart;
    private Button btnMainStop;
    MusicService musicService;
    ServiceConnection serviceConnection;
    boolean aBoolean=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        final Intent intent = new Intent(MainActivity.this, MusicService.class);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                musicService = ((MusicService.Service)service).getMusicService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                musicService = null;
            }
        };
        btnMainBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (aBoolean) {
                    bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                    btnMainBind.setText("解除绑定");
                    aBoolean = false;
                }else{
                    unbindService(serviceConnection);
                    btnMainBind.setText("绑定服务");
                    aBoolean = true;
                }
            }
        });
        btnMainStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicService.playMusic();
            }
        });
        btnMainStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicService.stopMusic();
            }
        });
    }

    private void initView() {
        textView = (TextView) findViewById(R.id.textView);
        btnMainBind = (Button) findViewById(R.id.btnMainBind);
        btnMainStart = (Button) findViewById(R.id.btnMainStart);
        btnMainStop = (Button) findViewById(R.id.btnMainStop);
    }
}